package com.zirenx.common.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.zirenx.sys.model.SysUser;
import com.zirenx.sys.service.SysUserService;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

	
	private SysUserService sysUserService = new SysUserService();
	
	/**
	 * 验证用户登录信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String name = String.valueOf(token.getPrincipal());
		SysUser user = sysUserService.login(name);
		if(user==null) {
			return null;
		}
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user , user.getPassword(),getName());

		return simpleAuthenticationInfo;
	}
	
	/**
	 * 验证用户权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		SysUser user = (SysUser)principals.getPrimaryPrincipal();
		if(user!=null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

			Set<String> userPerms = sysUserService.getUserPerms(user.getId());
			info.setStringPermissions(userPerms);

			return info;
		}
		return null;
	}
}
